package com.example.blogsystem.controller;


import com.example.blogsystem.constant.Constants;
import com.example.blogsystem.model.Blog;
import com.example.blogsystem.model.Result;
import com.example.blogsystem.model.User;
import com.example.blogsystem.service.BlogService;
import com.example.blogsystem.service.UserService;
import com.example.blogsystem.utils.EmailUtils;
import com.example.blogsystem.utils.JwtUtils;
import com.example.blogsystem.utils.SecurityUtils;
import com.example.blogsystem.utils.UploadFileUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RequestMapping("/user")
@RestController
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private BlogService blogService;

    //获取博客作者信息
    //查询博客作者信息和文章数
    @RequestMapping("/getAuthorInfo")
    public User getUserByBlogId(Integer blogId){
        //参数校验
        if(blogId == null || blogId <= 0){
            return null;
        }
        Blog blog = blogService.queryBlogById(blogId);
        User user = userService.getUserById(blog.getUserId());
        user.setArticleNumber(blogService.countArticles(blog.getUserId()));
        return user;
    }

    //获取当前登录的用户信息
    //查询用户信息和博客文章数
    @RequestMapping("/getUserInfo")
    public User getUser(HttpServletRequest request){
        Integer loginUserId = userService.getLoginUser(request);
        if(loginUserId == null){
            return null;
        }
        User user = userService.getUserById(loginUserId);
        //根据用户id计算文章个数
        user.setArticleNumber(blogService.countArticles(loginUserId));
        return user;
    }

    //用户登录
    @RequestMapping("/login")
    public Result userLogin(String userName, String password, HttpSession session) {
        //校验请求中的信息
        if (!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)) {
            return Result.fail("用户名或密码为空");
        }
        //获取数据库中请求的用户信息
        User user = userService.getUserByName(userName);
        if (user == null || !SecurityUtils.verify(password, user.getPassword())) {
            return Result.fail("用户名或密码不正确");
        }
        //使用session
        //session.setAttribute("SESSION_USER_KEY", user);
        //登录成功，返回token
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", user.getId());
        claims.put("userName", user.getUserName());
        String token = JwtUtils.genToken(claims);
        return Result.success(token);
    }

    //检查用户是否在期限时间的登录过
    @RequestMapping("/check")
    public Result userCheck(HttpServletRequest request){
        Integer loginUserId = userService.getLoginUser(request);

        if(loginUserId == null){
            return Result.fail("登录失败");
        }

        return Result.success("");
    }

    //发送验证码
    @RequestMapping("/sendCaptcha")
    public Result sendCaptcha(String email, HttpServletRequest request){

        //1.给客户端发送邮件
        String code = EmailUtils.sendCode(email);
        if(code == null){
            return Result.fail("邮箱格式非法");
        }
        //2.将验证码保存在session中
        HttpSession session = request.getSession();
        session.setAttribute(Constants.SESSION_EMAIL_CODE, code + System.currentTimeMillis());
        return Result.success("");
    }

    //用户注册功能
    @RequestMapping("/register")
    public Result registerUser(String userName, String password, String confirmPassword, String email, String captcha, HttpServletRequest request){
        if(!StringUtils.hasLength(userName) ||
                !StringUtils.hasLength(password) ||
                !StringUtils.hasLength(confirmPassword) ||
                !StringUtils.hasLength(email) ||
                !StringUtils.hasLength(captcha)){
            return Result.fail("用户输入为空");
        }
        User user = userService.getUserByName(userName);
        if(user != null){
            return Result.fail("用户已存在");
        }
        user = userService.getUserByEmail(email);
        if(user != null){
            return Result.fail("邮箱已被使用");
        }
        if(!password.equals(confirmPassword)){
            return Result.fail("两次密码不正确");
        }
        //校验验证码
        HttpSession session = request.getSession();
        String str = (String) session.getAttribute(Constants.SESSION_EMAIL_CODE);
        String emailCaptcha = str.substring(0, 5);
        long time = Long.parseLong(str.substring(5, str.length()));
        if(!emailCaptcha.equals(captcha) || (System.currentTimeMillis() - time > Constants.EMAIL_VALID_TIME)){
            return Result.fail("验证码失效或验证码错误");
        }
        //加密密码并插入数据库
        String sqlPassword = SecurityUtils.encrypt(password);
        userService.insertUser(new User(userName, sqlPassword, email));
        return Result.success("");
    }

    //根据邮箱找回密码
    @RequestMapping("/findPassword")
    public Result findPassword( String password, String confirmPassword, String email, String captcha, HttpServletRequest request){
        if(!StringUtils.hasLength(password)||
                !StringUtils.hasLength(confirmPassword) ||
                !StringUtils.hasLength(email) ||
                !StringUtils.hasLength(captcha)){
            return Result.fail("用户输入为空");
        }
        User user = userService.getUserByEmail(email);
        if(user == null){
            return Result.fail("用户不存在");
        }
        if(!password.equals(confirmPassword)){
            return Result.fail("两次密码不正确");
        }
        //校验验证码
        HttpSession session = request.getSession();
        String str = (String) session.getAttribute(Constants.SESSION_EMAIL_CODE);
        String emailCaptcha = str.substring(0, 5);
        long time = Long.parseLong(str.substring(5, str.length()));
        if(!emailCaptcha.equals(captcha) || (System.currentTimeMillis() - time > Constants.EMAIL_VALID_TIME)){
            return Result.fail("验证码失效或验证码错误");
        }
        //加密密码并插入数据库
        String sqlPassword = SecurityUtils.encrypt(password);
        user = new User();
        user.setPassword(sqlPassword);
        user.setEmail(email);
        userService.updatePassword(user);
        return Result.success("");
    }

    //更新用户信息
    @SneakyThrows
    @RequestMapping("/updateUser")
    public Result updateUser(HttpServletRequest request,
                             @RequestPart(value = "avatar", required = false) MultipartFile avatarFile,
                             String userName,
                             String githubUrl) {
        Integer loginUserId = userService.getLoginUser(request);
        User user = userService.getUserById(loginUserId);

        // 处理头像上传
        String avatarPath = "head/" + UploadFileUtils.uploadFile(avatarFile);

        if(StringUtils.hasLength(avatarPath)){
            user.setAvatarPath(avatarPath);
        }

        if(StringUtils.hasLength(userName)){
            user.setUserName(userName);
        }

        if(StringUtils.hasLength(githubUrl)){
            user.setGithubUrl(githubUrl);
        }
        // 保存用户信息
        userService.updateUser(user);

        return Result.success("");
    }

}
